package org.kgduyjj.toolbox.algorithms;

import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.kgduyjj.toolbox.DateUtil;

/**
 * 验证数字生成算法
 * 
 * @author Kgduyjj
 * @since 2020-07-26
 * @version Alpha-1.42
 *
 */
public final class VCodeGenerator {
	/** 正则表达式，非数字 */
	private static final Pattern NAN_PATTERN = Pattern.compile("[^0-9]");
	/** 日期格式化 */
	private static final String VCODE_FMT = "yyyyMMddHHmmssms";
	/** 空字符串 */
	private static final String EMPTY = "";
	/** 锁对象，可以为任意对象 */
	private static Integer lockObj = new Integer("20200201");
	private static final long DEFAULT_START_SORT = 0L;
	/** 订单号生成计数器 */
	private static long currentSortNo = DEFAULT_START_SORT;
	/** 每毫秒生成订单号数量最大值 */
	private static long maxSortSize = 1000;

	/**
	 * 匹配到字符串内所有的数字
	 * 
	 * @param text
	 * @return
	 */
	protected static String _matcherNumber(String text) {
		Matcher matcher = NAN_PATTERN.matcher(text);
		String numberText = matcher.replaceAll(EMPTY).trim();
		if (numberText != null && numberText.length() != 0)
			return numberText;
		return EMPTY;
	}

	/**
	 * 生成顺序号码，从0开始，根据位数获取x个0到x个9的顺序号码
	 * 
	 */
	protected static String genSortNumber() {
		String finOrderNum = EMPTY;
		try {
			synchronized (lockObj) {
				// 计数器到最大值归零，可扩展更大，目前1毫秒处理峰值1000个，1秒100万
				if (currentSortNo > maxSortSize) {
					currentSortNo = DEFAULT_START_SORT;
				}
				// 组装订单号
				String countStr = maxSortSize + currentSortNo + "";
				finOrderNum = countStr.substring(1);
				currentSortNo++;
				// Thread.sleep(1000);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
		return finOrderNum;
	}

	/**
	 * 生成原始标记
	 * 
	 * @param date
	 * @return
	 */
	protected static String _genOrginal(Date date) {
		if (date == null)
			date = new Date();
		StringBuffer buffer = new StringBuffer();
		// 当前时间，毫秒级
		buffer.append(DateUtil.format(date, VCODE_FMT));
		// 顺序号
		buffer.append(genSortNumber());
		return buffer.toString();
	}

	/**
	 * 生成原始标记
	 * 
	 * @return
	 */
	protected static String _genOrginal() {
		return _genOrginal(new Date());
	}
}
